import { IpcMainInvokeEvent } from 'electron';
import logger from 'electron-log';
import LogLevel from './log-level';
import fs from 'fs';
import path from 'path';

const TAG = 'LogUtil';
class Log {
  private static instance: Log;

  public static getInstance(): Log {
    if (!Log.instance) {
      Log.instance = new Log();
    }
    return Log.instance;
  }

  public init() {
    logger.transports.file.level = 'debug';
    logger.transports.console.level = 'debug';
    logger.transports.file.fileName = 'main.log';
    // 日志格式，默认：[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}]{scope} {text}
    logger.transports.file.format =
      '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}]{scope} {text}';
    // 日志大小，默认：1048576（1M），达到最大上限后，备份文件并重命名为：main.old.log，有且仅有一个备份文件
    logger.transports.file.maxSize = 50 * 1024 * 1024;
    Log.i(TAG, `init log util, log path: ${this.getLogPath()}`);
  }

  public getLogPath(): string {
    const logPath = logger.transports.file.file ?? '';
    return logPath;
  }

  public exportLog(event: IpcMainInvokeEvent, exportDir: string) {
    const logPath = Log.getInstance().getLogPath();
    const fileName = path.basename(logPath);
    const exportFileName = path.join(exportDir, fileName);
    fs.copyFile(Log.getInstance().getLogPath(), exportFileName, () => {});
  }

  public static e(...params: any[]) {
    logger.error(params);
  }

  public static w(...params: any[]) {
    logger.warn(params);
  }

  public static i(...params: any[]) {
    logger.info(params);
  }

  public static v(...params: any[]) {
    logger.verbose(params);
  }

  public static d(...params: any[]) {
    logger.debug(params);
  }

  public static s(...params: any[]) {
    logger.silly(params);
  }

  public static renderLog(
    event: IpcMainInvokeEvent,
    level: LogLevel,
    ...params: any[]
  ) {
    params.unshift('render thread log');
    switch (level) {
      case LogLevel.e:
        Log.e(params);
        break;
      case LogLevel.w:
        Log.w(params);
        break;
      case LogLevel.i:
        Log.i(params);
        break;
      case LogLevel.v:
        Log.v(params);
        break;
      case LogLevel.d:
        Log.d(params);
        break;
      case LogLevel.s:
        Log.s(params);
        break;
      default:
        break;
    }
  }
}
export default Log;
